<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="活动标题" prop="playName">
        <el-input
            v-model="queryParams.playName"
            placeholder="请输入活动标题"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="运动类型" prop="bizType">
        <el-select v-model="queryParams.bizType" placeholder="请选择运动类型" clearable>
          <el-option
              v-for="dict in play_sport_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="活动时间" prop="effTimeRange">
        <el-date-picker
            clearable
            v-model="effTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleEffTimeChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTimeRange">
        <el-date-picker
            clearable
            v-model="createTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleCreateTimeChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="发布状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择发布状态" clearable>
          <el-option
              v-for="dict in taptplay_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="上下架" prop="isPublish">
        <el-select v-model="queryParams.isPublish" placeholder="请选择上下架" clearable>
          <el-option
              v-for="dict in tprod_publish_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="活动状态" prop="effType">
        <el-select v-model="queryParams.effType" placeholder="请选择活动状态" clearable>
          <el-option
              v-for="dict in taptplay_efftype"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发布人" prop="userName">
        <el-input
            v-model="queryParams.userName"
            placeholder="请输入发布人"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="userPhone">
        <el-input
            v-model="queryParams.userPhone"
            placeholder="请输入手机号码"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--    <el-row :gutter="10" class="mb8">-->
    <!--      <el-col :span="1.5">-->
    <!--        <el-button-->
    <!--            type="primary"-->
    <!--            plain-->
    <!--            icon="Plus"-->
    <!--            @click="handleAdd"-->
    <!--            v-hasPermi="['system:taptplay:add']"-->
    <!--        >新增-->
    <!--        </el-button>-->
    <!--      </el-col>-->
    <!--      <el-col :span="1.5">-->
    <!--        <el-button-->
    <!--            type="danger"-->
    <!--            plain-->
    <!--            icon="Delete"-->
    <!--            :disabled="multiple"-->
    <!--            @click="handleDelete"-->
    <!--            v-hasPermi="['system:taptplay:remove']"-->
    <!--        >删除-->
    <!--        </el-button>-->
    <!--      </el-col>-->
    <!--      <el-col :span="1.5">-->
    <!--        <el-button-->
    <!--            type="warning"-->
    <!--            plain-->
    <!--            icon="Download"-->
    <!--            @click="handleExport"-->
    <!--            v-hasPermi="['system:taptplay:export']"-->
    <!--        >导出-->
    <!--        </el-button>-->
    <!--      </el-col>-->
    <!--      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>-->
    <!--    </el-row>-->

    <el-table v-loading="loading" :data="tplayList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="活动标题" align="center" prop="playName"/>
      <el-table-column label="运动类型" align="center" prop="bizType">
        <template #default="scope">
          <dict-tag :options="play_sport_type" :value="scope.row.bizType"/>
        </template>
      </el-table-column>
      <el-table-column label="活动地址" width="200" align="center" prop="addrDesc"/>
      <el-table-column label="活动时间" align="center" prop="effStartTime" width="150">
        <template #default="scope">
          <span>{{
              parseTime(scope.row.effStartTime, '{y}-{m}-{d} {h}:{i}')
            }}至{{ parseTime(scope.row.effEndTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发布状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="taptplay_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="上下架" align="center" prop="isPublish">
        <template #default="scope">
          <dict-tag :options="tprod_publish_type" :value="scope.row.isPublish"/>
        </template>
      </el-table-column>
      <el-table-column label="活动状态" align="center" prop="effType">
        <template #default="scope">
          <dict-tag :options="taptplay_efftype" :value="scope.row.effType"/>
        </template>
      </el-table-column>
      <el-table-column label="报名时间" align="center" prop="ext1" width="150">
        <template #default="scope">
          <span>{{
              parseTime(scope.row.ext1, '{y}-{m}-{d} {h}:{i}')
            }}至{{ parseTime(scope.row.ext2, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动人数" align="center" prop="ext3"/>
      <el-table-column label="报名人数" align="center" prop="userInfoCount"/>
      <el-table-column label="发布人" align="center" prop="userName"/>
      <el-table-column label="手机号码" align="center" prop="userPhone"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="350" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row, scope.index)"
                     v-hasPermi="['system:taptplay:query']">查看
          </el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:taptplay:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     :class="{'but-disabled': (scope.row.userInfoCount > 0)}"
                     v-hasPermi="['system:taptplay:remove']">删除
          </el-button>
          <el-button link type="primary" icon="User" @click="handleBuyer(scope.row)"
                     v-hasPermi="['system:taptplay:buyer']">报名
          </el-button>
          <el-button link type="primary" icon="Finished" @click="handlePublish(scope.row)"
                     :class="{'but-disabled': !(scope.row.isPublish === 0)}"
                     v-if="scope.row.isPublish === 0"
                     v-hasPermi="['system:taptplay:publish']">上架
          </el-button>
          <el-button link type="primary" icon="DocumentDelete" @click="handleCancelPublish(scope.row)"
                     :class="{'but-disabled': !(scope.row.isPublish === 1)}"
                     v-if="scope.row.isPublish === 1"
                     v-hasPermi="['system:taptplay:publish']">下架
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改活动列表对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="tplayRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="活动标题" prop="playName">
              <el-input v-model="form.playName" placeholder="请输入活动标题"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="主图" prop="playMainPic">
              <image-upload v-model="form.playMainPic" :limit="1"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详情图" prop="playDetailPic">
              <image-upload v-model="form.playDetailPic" :limit="9"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="约伴详情" prop="playDesc">
              <editor v-model="form.playDesc" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="活动类型" prop="bizType">
              <el-select v-model="form.bizType" placeholder="请选择活动类型">
                <el-option
                    v-for="dict in play_sport_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动人数" prop="ext3">
              <el-input-number v-model="form.ext3" :max="9999" :min="1" step-strictly/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="地区" prop="areaCode">
              <el-cascader-area v-model="form.areaCode" :qrtType="2"></el-cascader-area>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址" prop="addr">
              <el-input v-model="form.addr" type="textarea" placeholder="请输入详细地址"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <map-component :key="mapComponentKey"
                           :longitude="form.longitude" :latitude="form.latitude"
                           @coordinateClicked="handleCoordinateClicked"
            ></map-component>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="活动时间" prop="effStartTime">
              <el-date-picker
                  clearable
                  v-model="validTimeRange"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm"
                  @change="handleValidTimeChange"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报名时间" prop="ext1">
              <el-date-picker
                  :clearable="false"
                  v-model="saleTimeRange"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm"
                  @change="handleSaleTimeChange"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactName">
              <el-input v-model="form.contactName" maxlength="20" placeholder="请输入联系人"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="serviceTel">
              <el-input v-model="form.serviceTel"  maxlength="11" placeholder="请输入联系电话"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="活动详情" v-model="viewOpen" width="1000px" append-to-body>
      <el-form ref="tplayRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="活动标题" prop="playName" label-width="auto">
              {{ form.playName }}
              <!--              <el-input v-model="form.playName" placeholder="请输入活动标题" :disabled="true"/>-->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="主图" prop="playMainPic">
              <image-preview :src="form.playMainPic" :width="150" :height="150"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详情图" prop="playDetailPicList">
              <image-preview :src-list="form.playDetailPicList" :width="150" :height="150"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="约伴详情" prop="playDesc">
              <editor v-model="form.playDesc" :min-height="192" :readOnly="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="活动类型" prop="bizType">
              <el-select v-model="form.bizType" placeholder="请选择活动类型" :disabled="true">
                <el-option
                    v-for="dict in play_sport_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动人数" prop="ext3">
              <el-input-number v-model="form.ext3" :max="999999" :min="1" step-strictly :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="详细地址" prop="addr">
              <el-input v-model="form.addrDesc" type="textarea" placeholder="请输入详细地址" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="活动时间" prop="effStartTime">
              {{ parseTime(form.effStartTime, '{y}-{m}-{d} {h}:{i}') }} 至
              {{ parseTime(form.effEndTime, '{y}-{m}-{d} {h}:{i}') }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报名时间" prop="ext1">
              {{ parseTime(form.ext1, '{y}-{m}-{d} {h}:{i}') }} 至 {{ parseTime(form.ext2, '{y}-{m}-{d} {h}:{i}') }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactName">
              <el-input v-model="form.contactName" placeholder="请输入联系人" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="serviceTel">
              <el-input v-model="form.serviceTel" placeholder="请输入联系电话" type="number" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewOpen = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="报名列表" v-model="viewBuyer" width="500px" append-to-body>
      <el-form :model="queryBuyerParams" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item>
          <el-input
              v-model="queryBuyerParams.nickName"
              placeholder="请输入昵称或手机号"
              clearable
              @keyup.enter="getBuyerList"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="getBuyerList">搜索</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="buyerList" @selection-change="handleSelectionChange">
        <el-table-column label="昵称" align="center" prop="nickName"/>
        <el-table-column label="手机号" width="200" align="center" prop="phone"/>
      </el-table>
      <pagination
          v-show="buyerTotal>0"
          :total="buyerTotal"
          v-model:page="queryBuyerParams.pageNum"
          v-model:limit="queryBuyerParams.pageSize"
          @pagination="getBuyerList"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewBuyer = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Tplay">
import {
  listTplay,
  getTplay,
  delTplay,
  addTplay,
  updateTplay,
  updateStatus,
  updatePublish,
  getPlayBuyerList
} from "@/api/system/tplay";
import router from "@/router";
import {watch, onBeforeUnmount, ref} from "vue";
import useUserStore from "@/store/modules/user";
import MerSelect from "@/components/MerSelect/index.vue";
import {getAreaCode} from "@/api/system/sysCity";
import {ElMessage} from "element-plus";
import {getTmer} from "@/api/system/tmer";
import VideoOrimageUpload from "@/components/VideoOrimageUpload/index.vue";

const {proxy} = getCurrentInstance();
const {
  shop_type,
  t_status,
  t_mer_type,
  t_is_yes,
  play_sport_type,
  taptplay_status,
  tprod_publish_type,
  taptplay_efftype
} = proxy.useDict('shop_type', 't_status', 't_mer_type', 't_is_yes', 'play_sport_type', 'taptplay_status', 'tprod_publish_type', 'taptplay_efftype');

const tplayList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const validTimeRange = ref([]);
const disableNum = ref(0);
const mapComponentKey = ref(0);
const refreshTime = ref(0); //组件刷新次数
const effTimeRange = ref([]);
const createTimeRange = ref([]);
const viewOpen = ref(false);
const saleTimeRange = ref([]);
const viewBuyer = ref(false);
const buyerList = ref([]);
const buyerTotal = ref(0);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    merId: undefined,
    playName: undefined,
    playDesc: undefined,
    type: 4,
    bizHours: undefined,
    bizType: undefined,
    cityCode: undefined,
    areaCode: undefined,
    areaPath: undefined,
    addr: undefined,
    addrDesc: undefined,
    longitude: undefined,
    latitude: undefined,
    serviceTel: undefined,
    status: undefined,
    statusReason: undefined,
  },
  queryBuyerParams: {
    pageNum: 1,
    pageSize: 10,
    playId: undefined,
    nickName: undefined,
  },
  rules: {
    merId: [
      {required: true, message: "商家名称不能为空", trigger: "blur"}
    ],
    playName: [
      {required: true, message: "活动标题不能为空", trigger: "blur"}
    ],
    bizType: [
      {required: true, message: "运动类型不能为空", trigger: "blur"}
    ],
    // maxPeoples: [
    //   {required: true, message: "活动人数不能为空", trigger: "blur"}
    // ],
    effStartTime: [
      {required: true, message: "活动时间不能为空！", trigger: "change"},
    ],
    areaCode: [
      {required: true, message: "地区不能为空！", trigger: "change"},
    ],
    addr: [
      {required: true, message: "详细地址不能为空！", trigger: "change"},
    ],
    playMainPic: [
      {required: true, message: "主图不能为空", trigger: "blur"}
    ],
    playDetailPic: [
      {required: true, message: "详情图不能为空", trigger: "blur"}
    ],
    chatPic: [
      {required: true, message: "群聊码不能为空", trigger: "blur"}
    ],
    ext3: [
      {required: true, message: "活动人数不能为空", trigger: "blur"}
    ],
    ext1: [
      {required: true, message: "报名时间不能为空", trigger: "blur"}
    ],
    contactName: [
      {required: true, message: "联系人不能为空", trigger: "blur"}
    ],
    serviceTel: [
      {required: true, message: "联系电话不能为空", trigger: "blur"},
      { pattern: /^\d{1,11}$/, message: '请输入不超过11位的数字', trigger: 'blur' },
      { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur"}
    ],
    playDesc: [
      {required: true, message: "约伴详情不能为空", trigger: "blur"}
    ]
  }
});

const {queryParams, queryBuyerParams, form, rules} = toRefs(data);

/** 查询活动列表列表 */
function getList() {
  loading.value = true;
  listTplay(queryParams.value).then(response => {
    tplayList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    playId: undefined,
    merId: undefined,
    merName: undefined,
    playName: undefined,
    playMainPic: undefined,
    playDetailPic: undefined,
    playDesc: undefined,
    type: 2,
    bizHours: undefined,
    bizType: undefined,
    cityCode: undefined,
    areaCode: undefined,
    areaPath: undefined,
    addr: undefined,
    addrDesc: undefined,
    longitude: 118.8083,
    latitude: 31.8639,
    serviceTel: undefined,
    status: undefined,
    statusReason: undefined,
    auditTime: undefined,
    auditor: undefined,
    ext1: undefined,
    ext2: undefined,
    ext3: undefined,
    state: undefined,
    createTime: undefined,
    creator: undefined,
    modifyTime: undefined,
    modifier: undefined
  };
  mapComponentKey.value += 1;
  proxy.resetForm("tplayRef");
  validTimeRange.value = [];
  saleTimeRange.value = [];
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  effTimeRange.value = [];
  queryParams.value.effStartTime = null;
  queryParams.value.effEndTime = null;
  createTimeRange.value = [];
  queryParams.value.createStartTime = null;
  queryParams.value.createEndTime = null;
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  // ids.value = selection.map(item => item.playId);
  // single.value = selection.length != 1;
  // multiple.value = !selection.length;
  ids.value = selection.map(item => item.playId);
  single.value = selection.length != 1;
  let type = true
  if (selection.length == 1) {
    // 只选择一个
    if (selection[0].merStatus == '02' && selection[0].status == '00') {
      type = false
    } else {
      type = true
    }
  } else {
    // 选择多个
    type = false
    if (selection.length == 0) {
      type = true
    } else {
      selection.map(item => {
        if (item.merStatus !== '02' || item.status !== '00') {
          type = true
          return
        }
      })
    }

  }
  multiple.value = type
}

/** 新增按钮操作 */
function handleAdd() {
  disableNum.value = 0
  refreshTime.value += 1
  reset();
  open.value = true;
  title.value = "添加活动";
  mapComponentKey.value += 1;
}

function handleView(row) {
  const _merId = row.merId || ids.value;
  form.value = row;
  form.value.playDetailPicList = form.value.playDetailPic.split(",");
  console.log(form.value)
  viewOpen.value = true;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  disableNum.value = 1
  reset();
  const _playId = row.playId || ids.value
  getTplay(_playId).then(response => {
    form.value = response.data;
    validTimeRange.value = [response.data.effStartTime, response.data.effEndTime];
    saleTimeRange.value = [response.data.ext1, response.data.ext2];
    open.value = true;
    title.value = "修改活动";
    refreshTime.value += 1
    mapComponentKey.value += 1;
  });
}

function getBuyerList() {
  loading.value = true;
  getPlayBuyerList(queryBuyerParams.value).then(response => {
    buyerList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function handleBuyer(row) {
  queryBuyerParams.value.playId = row.playId;
  queryBuyerParams.value.nickName = undefined;
  getBuyerList();
  viewBuyer.value = true;
}

/** 提交按钮 */
function saveForm() {
  if (form.value.playDesc) {
    form.value.playDesc = form.value.playDesc.replace(/<img/g, '<img style="max-width: 100%;height: auto;"');
    form.value.playDesc = form.value.playDesc.replace('<iframe', `<video controls="" autoplay="" style="width: 100%;"`).replace('</iframe>', '</video>')
  }
  proxy.$refs["tplayRef"].validate(valid => {
    if (valid) {
      if (form.value.playId != null) {
        updateTplay(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTplay(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

function submitForm() {

  proxy.$refs["tplayRef"].validate(valid => {
    if (valid) {
      if (form.value.playId != null) {
        updateTplay(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTplay(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _playIds = row.playId || ids.value;
  proxy.$modal.confirm('是否确认删除活动编号为"' + _playIds + '"的数据项？').then(function () {
    return delTplay(_playIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

function handlePublish(row) {
  const _merIds = row.merId || ids.value;
  proxy.$modal.confirm('是否确认上架活动，编号为"' + _merIds + '"的数据项？').then(function () {
    row.isPublish = 1;
    return updatePublish(row);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("上架成功");
  }).catch(() => {
  });
}

function handleCancelPublish(row) {
  const _merIds = row.merId || ids.value;
  proxy.$modal.confirm('是否确认下架活动，编号为"' + _merIds + '"的数据项？').then(function () {
    row.isPublish = 0;
    return updatePublish(row);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("下架成功");
  }).catch(() => {
  });
}

function handleTerminate(row) {
  const _merIds = row.merId || ids.value;
  proxy.$modal.confirm('是否确认终止活动，编号为"' + _merIds + '"的数据项？').then(function () {
    row.status = "04";
    return updateStatus(row);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("终止成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/tplay/export', {
    ...queryParams.value
  }, `tplay_${new Date().getTime()}.xlsx`)
}

function handleValidTimeChange(value) {
  // if (value[0] < form.value.saleStartTime) {
  //   ElMessage.error('活动开始时间不能小于报名开始时间哦！')
  // }
  // if (value[1] < form.value.saleEndTime) {
  //   ElMessage.error('活动结束时间不能小于报名结束时间哦！')
  // }
  if (value && value.length === 2) {
    form.value.effStartTime = value[0];
    form.value.effEndTime = value[1];
  }
}

function handleSaleTimeChange(value) {
  if (value && value.length === 2) {
    form.value.ext1 = value[0];
    form.value.ext2 = value[1];
  }
}

function handleEffTimeChange(value) {
  if (value && value.length === 2) {
    queryParams.value.effStartTime = value[0];
    queryParams.value.effEndTime = value[1];
  } else {
    queryParams.value.effStartTime = null;
    queryParams.value.effEndTime = null;
  }
}

function handleCreateTimeChange(value) {
  if (value && value.length === 2) {
    queryParams.value.createStartTime = value[0];
    queryParams.value.createEndTime = value[1];
  } else {
    queryParams.value.createStartTime = null;
    queryParams.value.createEndTime = null;
  }
}

function handleCoordinateClicked(coordinate) {
  // 更新经纬度
  form.value.longitude = coordinate.lng;
  form.value.latitude = coordinate.lat;
  form.value.addr = coordinate.addr;
  getAreaCode({
    provinceExtName: coordinate.province,
    cityExtName: coordinate.city,
    districtExtName: coordinate.district
  }).then(response => {
    form.value.areaCode = response.data.district;
  });
}

onActivated(() => {
  getList();
})

getList();
// const stopWatching = watch(() => useUserStore().cascaderKey, (v) => {
//   getList();
// }, {immediate: true});
// onBeforeUnmount(() => {
//   stopWatching();
// });
</script>
